package com.example.knowledgeget1.FileOperate;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PdfService {
//    private final String API_URL = "https://api.textin.com/ai/service/v1/pdf_to_markdown";
    private final String API_URL="http://localhost:8010/convert";
    private final String APP_ID = "176f5c7c1cb6555d76e36feab4cc2d16";//"443dd647a8f14a2962034455ce9e37e0";
    private final String SECRET_KEY = "5dec126ac4e768d6df8e2310aa339c69";//"dc1243c9ef7d8086c8e1947007e2a2e3";
    private final String CHAT_API_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";

    @Value("${w.apikey}")
    private String authorizationHeader;
    public List<List<Map<String, Object>>> resolvePdf(MultipartFile file) throws IOException {
        List<List<Map<String, Object>>> results = new ArrayList<>();
        String API_URL = "http://localhost:8010/convert";
        CloseableHttpClient httpClient = HttpClients.createDefault();

        try {
            // 使用 MultipartEntityBuilder 来构建请求
            HttpPost httpPost = new HttpPost(API_URL);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            ContentType pdfContentType = ContentType.create("application/pdf");
            builder.addBinaryBody("pdf_file", file.getInputStream(), pdfContentType, file.getOriginalFilename());
            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);

            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);

            try {
                // 获取响应内容
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    String result = EntityUtils.toString(responseEntity, "UTF-8");

                    // 将响应解析为JSONArray
                    JSONArray jsonArray = new JSONArray(result);

                    // 假设我们需要处理每个JSON对象中的markdown字段
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        String markdown = jsonObject.getString("markdown");

                        // 假设这里有一个sendRequestToModel方法处理Markdown并返回JSON
                        String jsonChatResponse = sendRequestToModel(httpClient, markdown);
                        if (jsonChatResponse != null) {
                            List<Map<String, Object>> extractedData = extractJsonDataFromResponse(jsonChatResponse);
                            results.add(extractedData);
                        }
                    }
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.close();
        }

        return results;
    }
    private String sendRequestToModel(CloseableHttpClient httpClient, String prompt) {
        try {
            HttpPost httpPost = new HttpPost(CHAT_API_URL);
            httpPost.setHeader("Authorization", authorizationHeader);
            httpPost.setHeader("Content-Type", "application/json");

            String jsonPayload = new JSONObject()
                    .put("model", "qwen-long")
                    .put("messages", new JSONArray()
                            .put(new JSONObject().put("role", "system").put("content", "你是一个文本解析专家。下面有一段文本:"))
                            .put(new JSONObject().put("role", "system").put("content", prompt))
                            .put(new JSONObject().put("role", "user").put("content", "请仔细阅读文本，并去除所有Markdown格式（例如表格、标题等），将这段文本的主要领域，以章节 - 小节的目录列表树形式总结文件的内容部分。请使用如下JSON格式封装它们，其中是一个列表，每一个列表项包括一个id（id用来标识每一个列表项，从0开始）和一个提取到的章节名称列表chapters，一个章节名称列表项下包括该章节名称name和一个小节列表项sections，一个小节列表项下包括该小节的名称sectionName和该小节所讲的内容content。请确保content中的文本为纯文本格式，不含任何Markdown标记。")))
                    .toString();
            httpPost.setEntity(new StringEntity(jsonPayload, ContentType.APPLICATION_JSON));
//            httpPost.setEntity(new StringEntity(jsonPayload));
            System.out.println(jsonPayload);
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                if (response.getEntity() != null) {
                    String responseBody = EntityUtils.toString(response.getEntity());
                    System.out.println(responseBody);
                    return responseBody;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private List<Map<String, Object>> extractJsonDataFromResponse(String responseString) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        try {
            JSONObject jsonResponse = new JSONObject(responseString);
            JSONArray choices = jsonResponse.getJSONArray("choices");
            if (choices.length() > 0) {
                JSONObject choice = choices.getJSONObject(0);
                JSONObject message = choice.getJSONObject("message");
                String content = message.getString("content");
                int start = content.indexOf('[');
                int end = content.lastIndexOf(']');
                if (start == -1 || end == -1 || end < start) {
                    throw new IllegalArgumentException("Invalid JSON data in the string.");
                }
                content = content.substring(start, end+1);
                JSONArray jsonArray = new JSONArray(content);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject item = jsonArray.getJSONObject(i);
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", String.valueOf(item.getInt("id")));

                    JSONArray chaptersArray = item.getJSONArray("chapters");
                    List<Map<String, Object>> chaptersList = new ArrayList<>();

                    for (int j = 0; j < chaptersArray.length(); j++) {
                        JSONObject chapterItem = chaptersArray.getJSONObject(j);
                        Map<String, Object> chapterMap = new HashMap<>();

                        chapterMap.put("name", chapterItem.getString("name"));

                        JSONArray sectionsArray = chapterItem.getJSONArray("sections");
                        List<Map<String, String>> sectionsList = new ArrayList<>();

                        for (int k = 0; k < sectionsArray.length(); k++) {
                            JSONObject sectionItem = sectionsArray.getJSONObject(k);
                            Map<String, String> sectionMap = new HashMap<>();
                            sectionMap.put("sectionName", sectionItem.getString("sectionName"));
                            sectionMap.put("content", sectionItem.getString("content"));
                            sectionsList.add(sectionMap);
                        }

                        chapterMap.put("sections", sectionsList);
                        chaptersList.add(chapterMap);
                    }

                    map.put("chapters", chaptersList);
                    resultList.add(map);
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultList;
    }
}
